<?php
class ProductsController extends StoreAppController {

	var $name = 'StoreProducts';
	var $pageTitle = null;
	var $permissions = array(
		'add' => array('admin','manag'),
		'index' => '*',
		'edit' => array('admin','manag'),
		'delete' => array('admin','manag'),
		'delete_file' => array('admin','manag'),
		'admin_index' => array('admin','manag')
	);
	
	
	public $presetVars = array(
		array('field' => 'full_text_serch', 'type' => 'like')
		,array('field' => 'model_id', 'type' => 'value')
		,array('field' => 'price_detaliczna', 'type' => 'range')
		
	);
		
	public function beforeFilter(){
		parent::beforeFilter();
		App::import('Model','Store.StoreCategory'); 
 		$this->StoreCategory = new StoreCategory();		
		App::import('Model','Store.StoreTypeGroup');
		$this->StoreTypeGroup = new StoreTypeGroup();		
		App::import('Model','Store.StoreProductMatch');
		$this->StoreProductMatch = new StoreProductMatch();
		
		$this->set_display_type();
		
//		$this->layout = 'cms';	
	}
	function beforeRender(){
		parent::beforeRender();
		// nazwa strony i keywords
		$this->setup_page();		
	}
	
	function afterFilter(){
		parent::afterFilter();
		
	}
	
	private function set_display_type(){
		if (isset($this->params['named']['display'])){
			switch($this->params['named']['display']){
				case 'list':
					$this->Session->write('Store.display','display_list');
					break;
				case 'icons':
					$this->Session->write('Store.display','display_icon');
					break;
			}
		}else{
			$displ = $this->Session->read('Store.display');
			if(empty($displ))
			$this->Session->write('Store.display','display_icon');
		}		
	}
	
	private function setup_page(){
		if ($this->params['action'] == 'view' && isset($this->params['pass'][0])){
			$this->StoreProduct->recursive = 0;
			$storeProduct = $this->StoreProduct->read(null, $this->params['pass'][0]);
			

			if($storeProduct['StoreProduct']['price_przecena'] > 0 && $storeProduct['StoreProduct']['price_promocja'] == 0){
				$price = $storeProduct['StoreProduct']['price_przecena'].' '.$storeProduct['StoreProduct']['currency_id'];
			}else if( $storeProduct['StoreProduct']['price_promocja'] > 0){
				$price = $storeProduct['StoreProduct']['price_promocja'].' '.$storeProduct['StoreProduct']['currency_id'];
			}else{
				$price = $storeProduct['StoreProduct']['price_detaliczna'].' '.$storeProduct['StoreProduct']['currency_id'];
			}
						
			$title = $storeProduct['StoreProduct']['name'] . ' - ' . $price;
			$this->set("title_for_layout",$title);
			$keywords = (isset($storeProduct['StoreProduct']['keywords'])) ? $storeProduct['StoreProduct']['keywords'] : '';
			$this->set('keywords_for_layout_cms',$keywords);
		}else{
			return false;
		}		
	}
	
	
	
	function index(){
		$this->layout = 'default';
	}
	
	public function admin_index($category_id = 0){
		$joins = array();
		$conditions = array();
		$order = array('StoreProduct.lp_categ' => 'ASC');
		$conditions['StoreProduct.active'] = 1;
		if ($category_id != 0) {
			$category = $this->StoreCategory->read(null, $category_id);
			array_push($joins, array('table' => 'store_product_categories', 'alias' => 'StoreProductCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.product_id = StoreProduct.id')));
			array_push($joins, array('table' => 'store_categories', 'alias' => 'StoreCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.category_id = StoreCategory.id')));
			
			//$conditions['StoreProductCategory.category_id'] = $category_id;
			$conditions['StoreCategory.lft >= '] = $category['StoreCategory']['lft'];
			$conditions['StoreCategory.rght <= '] = $category['StoreCategory']['rght'];
		}
		
		$this->paginate = array('conditions' => $conditions,'limit' => 20,'joins'=>$joins,'order'=>$order);
		$this->StoreProduct->recursive = 1;
		$products = $this->paginate('StoreProduct');
		
		$this->set('storeProducts', $products);	
	}
	
	private function _lp_categ($category_id=null){
		$joins = array();
		$conditions = array();
		if ($category_id != null) {
			//$category = $this->StoreProduct->StoreCategory->read(null, $category_id);
			array_push($joins, array('table' => 'store_product_categories', 'alias' => 'StoreProductCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.product_id = StoreProduct.id')));
			$conditions['StoreProductCategory.category_id'] = $category_id;
			$lp_categ = $this->StoreProduct->find('first',array('joins'=>$joins,'conditions'=>$conditions,'fields'=>array('MAX(StoreProduct.lp_categ) AS lp'), 'group' => 'StoreProductCategory.category_id'));
			return $lp_categ['0']['lp']+1;		
		}else{
			return 0;
		}
	}
	
	function display($category_id = null){	
		$joins = array();
		$conditions = array();
		$order = array('StoreProduct.added' => 'DESC');
		$conditions['StoreProduct.active'] = 1;
		$display_categories = true;
		if(isset($this->params['named']['group_id']) && is_numeric($this->params['named']['group_id'])){
			$conditions['StoreProduct.group_id'] = $this->params['named']['group_id'];
			$storeGroupName = $this->StoreProduct->StoreGroup->field('name',array('StoreGroup.id'=>$this->params['named']['group_id']));
			$this->set('storeGroupName', $storeGroupName);	
			$display_categories = false;
		}
		if(isset($this->params['named']['model_id']) && is_numeric($this->params['named']['model_id'])){
			// wersja gdy model_id w StoreProduct
//			$conditions['StoreProduct.model_id'] = $this->params['named']['model_id'];

			//multi select dla model
			array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
			array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
			$conditions['StoreModel.id'] = $this->params['named']['model_id'];
			
			
//			$storeGroupName = $this->StoreProduct->StoreGroup->field('name',array('StoreGroup.id'=>$this->params['named']['group_id']));
//			$this->set('storeGroupName', $storeGroupName);	
			$display_categories = false;
		}
		
//		if(isset($this->params['named']['type_group_id']) && is_numeric($this->params['named']['type_group_id'])){
//			array_push($joins, array('table' => 'store_product_types', 'alias' => 'StoreProductType', 'type' => 'INNER', 'conditions' => array( 'StoreProductType.product_id = StoreProduct.id')));
//			$conditions['StoreProductType.for'] = 1;
////			array_push($joins, array('table' => 'store_types', 'alias' => 'StoreType', 'type' => 'INNER', 'conditions' => array( 'StoreProductType.type_id = StoreType.id')));
//			
//		}
		if ($category_id != null && is_numeric($category_id)) {
			$category = $this->StoreCategory->read(null, $category_id);
			$this->set("title_for_layout",$category['StoreCategory']['name']);
			$this->set('storeGroupName', $category['StoreCategory']['name']);
			$this->set('selectedCategoryID', $category['StoreCategory']['id']);
			array_push($joins, array('table' => 'store_product_categories', 'alias' => 'StoreProductCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.product_id = StoreProduct.id')));
			array_push($joins, array('table' => 'store_categories', 'alias' => 'StoreCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.category_id = StoreCategory.id')));
			$conditions['StoreCategory.lft >= '] = $category['StoreCategory']['lft'];
			$conditions['StoreCategory.rght <= '] = $category['StoreCategory']['rght'];
		}elseif($display_categories){
			$this->set('display_categories', $this->StoreCategory->find('all'));	
		}

		if(!isset($this->params['named']['model_id'])){
			switch($category_id){
				case 'special-occasion':
					array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = 3;				
					break;
				case 'specjal-offers':
					array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = 4;
					break;
				case 'casual':
					array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = 5;
					break;
				case 'wedding-collection':
					array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = 6;
					break;	
				case 'exclusive-jewellery':
					array_push($joins, array('table' => 'store_product_models', 'alias' => 'StoreProductModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.product_id = StoreProduct.id')));
					array_push($joins, array('table' => 'store_models', 'alias' => 'StoreModel', 'type' => 'INNER', 'conditions' => array( 'StoreProductModel.model_id = StoreModel.id')));
					$conditions['StoreModel.id'] = 12;
					break;
				case 'moust_viewed':
					$order = array('StoreProduct.viewed DESC' );
					break;
			}
		}
		
		$this->paginate = array('conditions' => $conditions,'limit' => 12,'joins'=>$joins,'order'=>$order);
		$this->StoreProduct->recursive = 0;
		$products = $this->paginate('StoreProduct');
		$this->set('storeProducts', $products);	
		$this->set('category_id', $category_id);
	}
	
	public function search() {
		$this->Prg->commonProcess();
		$this->paginate['limit'] = 12;
		$this->paginate['conditions'] = $this->StoreProduct->parseCriteria($this->passedArgs);
		$storeProducts = $this->paginate();
		$storeGroupName = __('Search Results',true);
		$this->set(compact('storeProducts','storeGroupName'));
	}

	function view($id = null){
		if (!$id){
			$this->Session->setFlash(__d('store','Invalid store product', true));
			$this->redirect($this->referer());
		}
//		unset($this->StoreProduct->belongsTo['StoreUpload']);
		$this->StoreProduct->recursive = 1;
		$storeProduct = $this->StoreProduct->read(null, $id);
		
		// rozdzielenie types wg type_group
		if(is_array($storeProduct['StoreType'])){
			$storeProductTypes = array();
			foreach ($storeProduct['StoreType'] as $key => $type) {
				$storeProductTypes[$type['StoreProductType']['for_group']][$key] = $type;				
			}
		}
		$storeTypeGroup = $this->StoreTypeGroup->find('list');
		$selectedCategoryID = (isset($storeProduct['StoreCategory'][0]['id'])) ? $storeProduct['StoreCategory'][0]['id'] : null;
		
		/*powiazane produkty*/
		$this->StoreProductMatch->recursive = 2;
		$storeMatchProducts = $this->StoreProductMatch->find('all',
			array(
				'conditions'=>array('product_id'=>$storeProduct['StoreProduct']['id'])
			));
			
		// uppdate viewed
//		$this->StoreProduct->read(null,$id);
//		$this->StoreProduct->set('StoreProduct.viewed', 111);
		$this->StoreProduct->query('UPDATE '.$this->StoreProduct->useTable.' SET viewed  = viewed + 1 WHERE id = '.$id );
		
			
		$this->set(compact('storeProduct','storeTypeGroup','storeProductTypes','selectedCategoryID','storeMatchProducts'));
		$this->layout = 'default';
	}
	
	function export($id = null){
		if (!$id){
			$this->Session->setFlash(__d('store','Invalid store product', true));
			$this->redirect($this->referer());
		}
		$product = $this->StoreProduct->read(null, $id);
		$this->set('storeProduct', $product);
		
        $sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"manag"))); // moderators
    	if(is_array($sprzedawca) && !empty($sprzedawca)){
    	}else{
    		$sprzedawca = $this->User->find('first',array('conditions'=>array('User.group'=>"admin")));
    	}    	
		$this->set('sprzedawca', $sprzedawca);
		
		$this->layout = 'export';
	}

	function add() {
		
		if (!empty($this->data)) {	
			
			$this->transaction->begin($this);
			
			if($this->FileUpload->success){
				$image_path = ROOT.DS.'app'.DS.'webroot'.DS.'files'.DS.HOST.DS.'upload'.DS.$this->FileUpload->file();
				
				$this->data['StoreProduct']['upload_id'] = $this->StoreProduct->StoreUpload->getLastInsertID();
				$this->data['StoreProduct']['added'] = date('Y-m-d H:i:s');
				
				$lp_group = $this->StoreProduct->find('first',array('conditions'=>array('StoreProduct.group_id'=>$this->data['StoreProduct']['group_id']),'fields'=>array('MAX(StoreProduct.lp_group) AS lp'), 'group' => 'StoreProduct.group_id'));
				$this->data['StoreProduct']['lp_group'] = $lp_group['0']['lp']+1;

				$lp_categ = $this->_lp_categ($this->data['StoreProductCategory']['category_id']);
				$this->data['StoreProduct']['lp_categ'] = $lp_categ;
				$this->data['StoreProduct']['stan'] = 0;
				
				$this->StoreProduct->create();
				if ($this->StoreProduct->save($this->data)){					
					$this->data['StoreProductCategory']['product_id'] = $this->StoreProduct->getLastInsertID();
					$type['StoreProductType']['product_id'] = $this->data['StoreProductCategory']['product_id']; 
					$this->StoreProduct->StoreProductCategory->create();
					if ($this->StoreProduct->StoreProductCategory->save($this->data)){						
						$this->Session->setFlash(__d('store','The store product has been saved', true));
						if(isset($this->data['StoreType'])){
							foreach ($this->data['StoreType']['type_id'] as $type_id => $select) {
								if($select && 
									isset($this->data['StoreType']['inventory'][$type_id]) && 
									$this->data['StoreType']['inventory'][$type_id] > 0  &&
									is_numeric($this->data['StoreType']['inventory'][$type_id])
								){
									$type['StoreProductType']['type_id'] = $type_id;
									$type['StoreProductType']['inventory'] = $this->data['StoreType']['inventory'][$type_id];
									$type['StoreProductType']['for_group'] = $this->data['StoreType']['for_group'][$type_id];	

									$this->data['StoreProduct']['stan'] = $this->data['StoreProduct']['stan'] +  $this->data['StoreType']['inventory'][$type_id];
									
									$this->StoreProduct->StoreProductType->create();
									$this->StoreProduct->StoreProductType->save($type);
								}
							}
						}

						// zapis sanu wszystkich typów
						$this->StoreProduct->query('UPDATE '.$this->StoreProduct->useTable.' SET stan  = '.$this->data['StoreProduct']['stan'].' WHERE id = '.$this->data['StoreProductCategory']['product_id'] );
						
						$this->transaction->commit($this);
						$this->redirect(array('action'=>'view',$this->data['StoreProductCategory']['product_id']));
					}else{
						$this->Session->setFlash(__d('store','The store product could not be saved. Please, try again.', true));					
					}					
					
				} else {
					$this->Session->setFlash(__d('store','The store product could not be saved. Please, try again.', true));
				}
				$this->transaction->rollback($this);
			}
		}
		$storeUploads = $this->StoreProduct->StoreUpload->find('list');
		$storeGroups = $this->StoreProduct->StoreGroup->find('list');
		$storeTaxes = $this->StoreProduct->StoreTax->find('list');
		$storeUnits = $this->StoreProduct->StoreUnit->find('list');
		$storeTypes = $this->StoreProduct->StoreType->find('all',array('conditions'=>array('StoreType.category_id'=>0)));
		$storeTypeGroup = $this->StoreTypeGroup->find('list',array('order'=>array('default_group_id','name')));
		$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>0)));
		$storeCurrencies = $this->StoreProduct->StoreCurrency->find('list',array('conditions'=>array('StoreCurrency.active'=>1)));
		$parentCategory = $this->StoreCategory->find('threaded', array());
		$parentCategories = $this->treeForCombobox($parentCategory,'StoreCategory');
	    
		$this->set(compact('storeUploads', 'storeGroups', 'storeTaxes', 'storeUnits', 'storeTypes','storeTypeGroup','parentCategories','storeModels','storeCurrencies'));	
		
	}
	
	function product_types($id = null){
		if($this->RequestHandler->isAjax()) {
			Configure::write('debug', 0);
			
			//$storeTypeGroup = $this->StoreTypeGroup->find('list');
			$storeTypeGroup = $this->StoreTypeGroup->find('list',array('order'=>array('default_group_id','name')));
			if(isset($this->params['url']['category_id']) && is_numeric($this->params['url']['category_id'])){
				$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>$this->params['url']['category_id'])));
				$storeTypes = $this->StoreProduct->StoreType->find('all',array('conditions'=>array('StoreType.category_id'=>$this->params['url']['category_id'])));
				if(empty($storeTypes)){
					$storeTypes = $this->StoreProduct->StoreType->find('all',array('conditions'=>array('StoreType.category_id'=>0)));
				}
				if(empty($storeModels)) {
					$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>0)));
				}
				$this->set(compact('storeTypes','storeTypeGroup','storeModels'));
			}else{
				$this->set('nocategory','nocategory');
			}			
			
		}
	}
	

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__d('store','Invalid store product', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			$this->transaction->begin($this);
			if($this->FileUpload->success){	
				
				$product = $this->StoreProduct->findById($id);
				// delete old upload file
	    		$this->StoreProduct->StoreUpload->delete($product['StoreProduct']['upload_id']);
	    		$this->delete_file($product['StoreProduct']['upload_id']);	

	    		$this->data['StoreProduct']['upload_id'] = $this->StoreProduct->StoreUpload->getLastInsertID();	    		
			}

			
			$this->data['StoreProduct']['stan'] = 0;
			foreach ($this->data['StoreType']['type_id'] as $type_id => $select) {
				if($select && 
					isset($this->data['StoreType']['inventory'][$type_id]) && 
					$this->data['StoreType']['inventory'][$type_id] > 0  &&
					is_numeric($this->data['StoreType']['inventory'][$type_id])
				){
					$this->data['StoreProduct']['stan'] += $this->data['StoreType']['inventory'][$type_id];
				}
			}
			unset($this->data['StoreUpload']); // trzeba usunac bo usuwa gallerie
			$this->StoreProduct->id = $this->data['StoreProduct']['id'];
			if ($this->StoreProduct->save($this->data)) {
				$this->data['StoreProductCategory']['product_id'] = $this->data['StoreProduct']['id'];				
				if(isset($this->data['StoreProductCategory']['id'])){
					$this->StoreProduct->StoreProductCategory->id = $this->data['StoreProductCategory']['id'];
				}else{
					$this->StoreProduct->StoreProductCategory->create();
				}
				if (!$this->StoreProduct->StoreProductCategory->save($this->data)){
					$this->Session->setFlash(__d("store","Zmiana kategorii nie zostala zapisana", true));
				}
				
				if($this->StoreProduct->StoreProductModel->deleteAll(array('StoreProductModel.product_id'=>$this->data['StoreProduct']['id']))){
					if(isset($this->data['StoreModel']['StoreModel']) && is_array($this->data['StoreModel']['StoreModel'])){
						foreach ($this->data['StoreModel']['StoreModel'] as $key_model => $model_id) {
							if(is_numeric($model_id) ){
								$product_model= array();
								$product_model['StoreProductModel']['product_id'] = $this->data['StoreProduct']['id'];
								$product_model['StoreProductModel']['model_id'] = $model_id;
								$this->StoreProduct->StoreProductModel->create();
								$this->StoreProduct->StoreProductModel->save($product_model);
							}
						}
					}
				}				
								
				if($this->StoreProduct->StoreProductType->deleteAll(array('StoreProductType.product_id'=>$this->data['StoreProduct']['id']))){
					if(isset($this->data['StoreType']['type_id']) && is_array($this->data['StoreType']['type_id'])){
						foreach ($this->data['StoreType']['type_id'] as $type_id => $select) {
							if($select && 
								isset($this->data['StoreType']['inventory'][$type_id]) && 
								$this->data['StoreType']['inventory'][$type_id] > 0  &&
								is_numeric($this->data['StoreType']['inventory'][$type_id])
							){
								$type['StoreProductType']['product_id'] = $this->data['StoreProduct']['id'];
								$type['StoreProductType']['type_id'] = $type_id;
								$type['StoreProductType']['inventory'] = $this->data['StoreType']['inventory'][$type_id];	
								$type['StoreProductType']['for_group'] = $this->data['StoreType']['for_group'][$type_id];							
								$this->StoreProduct->StoreProductType->create();
								$this->StoreProduct->StoreProductType->save($type);
							}
						}
					}
				}				
				$this->Session->setFlash(__d('store','The store product has been saved', true));
				$this->transaction->commit($this);
				$this->redirect($this->referer());
			} else {				
				$this->Session->setFlash(__d('store','The store product could not be saved. Please, try again.', true));
			}				
			$this->transaction->rollback($this);
			$this->redirect($this->referer());
		}
		if (empty($this->data)) {
			$this->data = $this->StoreProduct->read(null, $id);
		}
		
		$parentCategory = $this->StoreCategory->find('threaded', array());
		$parentCategories = $this->treeForCombobox($parentCategory,'StoreCategory');
        
		$storeUploads = $this->StoreProduct->StoreUpload->find('list');
		$storeGroups = $this->StoreProduct->StoreGroup->find('list');
		$storeTaxes = $this->StoreProduct->StoreTax->find('list');
		$storeUnits = $this->StoreProduct->StoreUnit->find('list');
		if(is_array($this->data) && isset($this->data['StoreCategory'][0]['id'])){		
		
			$storeTypes = $this->StoreProduct->StoreType->find('list',array('conditions'=>array('StoreType.category_id'=>$this->data['StoreCategory'][0]['id'])));
			$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>$this->data['StoreCategory'][0]['id'])));			
			
			if(empty($storeTypes)) {
				$storeTypes = $this->StoreProduct->StoreType->find('list',array('conditions'=>array('StoreType.category_id'=>0)));
			}
			if(empty($storeModels)) {
				$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>0)));
			}
		}else{
			$storeTypes = $this->StoreProduct->StoreType->find('list',array('conditions'=>array('StoreType.category_id'=>0)));
			$storeModels = $this->StoreProduct->StoreModel->find('list',array('conditions'=>array('StoreModel.category_id'=>0)));
		}
		
		
		// gdy zmieniamy polaczenie category_id <=> type_id w prducjie zostaja stare polaczenie product_id <=> type_id 
		$usedTypes = $this->StoreProduct->StoreProductType->find('list',array('conditions'=>array('StoreProductType.product_id'=>$this->data['StoreProduct']['id']),'fields'=>'StoreProductType.type_id,StoreProductType.type_id'));
		$unused = array_diff_key($usedTypes,$storeTypes);
		if(is_array($unused) && !empty($unused)){
			$oldUsedTypes = $this->StoreProduct->StoreType->find('list',array('conditions'=>array('StoreType.id'=>$unused)));
			foreach ($oldUsedTypes as $key => $tpe) {				
				$storeTypes[$key] = $tpe;
			}			
		}
		$storeTypeGroup = $this->StoreTypeGroup->find('list');
		$storeCurrencies = $this->StoreProduct->StoreCurrency->find('list',array('conditions'=>array('StoreCurrency.active'=>1)));
		/*powiazane produkty*/
		$this->StoreProductMatch->recursive = 2;
		$storeMatchProducts = $this->StoreProductMatch->find('all',
			array(
				'conditions'=>array('product_id'=>$this->data['StoreProduct']['id'])
			));
		$this->set(compact('storeMatchProducts','storeUploads', 'storeGroups', 'storeTaxes', 'storeUnits', 'storeTypes','storeTypeGroup','parentCategories','storeModels','storeCurrencies'));
	}
	
	function add_match($product_id=null){

		if (empty($this->data)) {
			if (!$product_id) {
				$this->Session->setFlash(__d('store','Invalid id for store product', true));
				$this->redirect($this->referer());
			}
			$this->data['StoreProductMatch']['product_id'] = $product_id;
			$this->StoreProduct->recursive = 1;
			$storeProducts = $this->StoreProduct->find('all',array('conditions'=>array('StoreProduct.id !='=>$product_id)));
			$this->set('storeProducts',$storeProducts);
		}else{
			if(is_array($this->data['StoreProductMatch']['match_product_id']) && !empty($this->data['StoreProductMatch']['match_product_id'])){
				$this->transaction->begin($this);
				foreach ($this->data['StoreProductMatch']['match_product_id'] as $match_product_id => $checked) {
					if($checked){
						$add_match = array();
						$add_match['StoreProductMatch']['product_id'] = $this->data['StoreProductMatch']['product_id'];
						$add_match['StoreProductMatch']['match_product_id'] = $match_product_id;
						$add_match['StoreProductMatch']['sets'] = (isset($this->data['StoreProductMatch']['sets'][$match_product_id])) ? $this->data['StoreProductMatch']['sets'][$match_product_id] : 0;
						$this->StoreProductMatch->create();
						if ($this->StoreProductMatch->save($add_match)){
							
						}else{
							$this->transaction->rollback($this);
							$this->Session->setFlash(__d('store','Not saved the selected products. Please try again.', true));
							$this->redirect(array('plugin'=>'store','controller'=>'products', 'actions'=>'edit',$this->data['StoreProductMatch']['product_id']));
						}
					}
				}
			}
			$this->transaction->commit($this);
			$this->Session->setFlash(__d('store','Added the selected products successfully.', true));
			$this->redirect(array('plugin'=>'store','controller'=>'products', 'action'=>'edit',$this->data['StoreProductMatch']['product_id']));
		}
	}
	
	function delete_match($product_id = null,$match_product_id=null) {
		if (!$product_id) {
			$this->Session->setFlash(__d('store','Invalid id for store product', true));
			$this->redirect($this->referer());
		}
		if ($this->StoreProductMatch->deleteAll(array('StoreProductMatch.product_id'=>$product_id,'StoreProductMatch.match_product_id'=>$match_product_id))) {
			$this->Session->setFlash(__d('store','Matched product deleted', true));
			$this->redirect($this->referer());
		}
		$this->Session->setFlash(__d('store','Matched product was not deleted', true));
		$this->redirect($this->referer());
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__d('store','Invalid id for store product', true));
			$this->redirect($this->referer());
		}
		if ($this->StoreProduct->delete($id)) {
			$this->Session->setFlash(__d('store','Store product deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__d('store','Store product was not deleted', true));
		$this->redirect($this->referer());
	}
	
	private function delete_file($upload_id = null) {
	    $upload =  $this->StoreProduct->StoreUpload->findById($upload_id);	    
	    if($this->FileUpload->removeFile($upload['StoreUpload']['name'])){
			if($this->StoreProduct->StoreUpload->delete($upload['StoreUpload']['id'])){
	        	$this->Session->setFlash(__d('store','Store product deleted', true));
			}else{
				$this->Session->setFlash(__d('store','The picture could not be deleted from Upload. Please, try again.', true));
			}
	    }else{
	    	$this->Session->setFlash(__d('store','The picture could not be deleted from Disc. Please, try again.', true));
	    }
	}
	
	/**
	 * 
	 * okreslenie porzadku wg pola lp_... w grupie lub kategorii
	 * @param $id
	 * @param $lp
	 * @param $file
	 */
	function up($id=null,$lp = 'lp_group',$file='group_id'){
		
		$a = $this->StoreProduct->read(null, $id);
		if($file == 'group_id'){
			$b = $this->StoreProduct->find('first',array(
		        'conditions' => array(
					"StoreProduct.{$file} = " =>$a['StoreProduct'][$file],
					"StoreProduct.{$lp} = " => $a['StoreProduct'][$lp] - 1				
				)));
		}else{
			$joins = array();
			$conditions = array();
			if ($id != null) {
				$c = $this->StoreProduct->StoreProductCategory->find('first',array(
			        'conditions' => array(
						"StoreProductCategory.product_id" => $id			
					)));
				$category = $this->StoreProduct->StoreCategory->read(null, $c['StoreProductCategory']['category_id']);
				array_push($joins, array('table' => 'store_categories', 'alias' => 'StoreCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.category_id = StoreCategory.id')));
				array_push($joins, array('table' => 'store_product_categories', 'alias' => 'StoreProductCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.product_id = StoreProduct.id')));
				//$conditions['StoreProductCategory.category_id'] = $c['StoreProductCategory']['category_id'];
				$conditions['StoreCategory.lft >= '] = $category['StoreCategory']['lft'];
				$conditions['StoreCategory.rght <= '] = $category['StoreCategory']['rght'];
				$conditions["StoreProduct.{$lp}"] = $a['StoreProduct'][$lp] - 1;
				$b = $this->StoreProduct->find('first',array('joins'=>$joins,'conditions'=>$conditions));
			}else{
				$b = null;
			}			
		}
			
		if(is_array($a) && !empty($a)){
			$a['StoreProduct'][$lp] = (isset($a['StoreProduct'][$lp]) && $a['StoreProduct'][$lp] > 1 ) ? $a['StoreProduct'][$lp] - 1 : 1;
			$this->StoreProduct->save($a);
			if(is_array($b) && !empty($b)){
				$b['StoreProduct'][$lp] = (isset($b['StoreProduct'][$lp]) ) ? $b['StoreProduct'][$lp] + 1 : 0;
				$this->StoreProduct->save($b);	
			}			
		}
		$this->redirect($this->referer());
	}	
	
	function down($id=null,$lp = 'lp_group',$file='group_id'){
				
		$a = $this->StoreProduct->read(null, $id);		
		if($file == 'group_id'){
			$b = $this->StoreProduct->find('first',array(
		        'conditions' => array(
					"StoreProduct.{$file} = " =>$a['StoreProduct'][$file],
					"StoreProduct.{$lp} = " => $a['StoreProduct'][$lp] + 1				
				)));
		}else{
			$joins = array();
			$conditions = array();
			if ($id != null) {
				$c = $this->StoreProduct->StoreProductCategory->find('first',array(
			        'conditions' => array(
						"StoreProductCategory.product_id" => $id			
					)));
				$category = $this->StoreProduct->StoreCategory->read(null, $c['StoreProductCategory']['category_id']);
				array_push($joins, array('table' => 'store_categories', 'alias' => 'StoreCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.category_id = StoreCategory.id')));
				array_push($joins, array('table' => 'store_product_categories', 'alias' => 'StoreProductCategory', 'type' => 'INNER', 'conditions' => array( 'StoreProductCategory.product_id = StoreProduct.id')));
				//$conditions['StoreProductCategory.category_id'] = $c['StoreProductCategory']['category_id'];
				$conditions['StoreCategory.lft >= '] = $category['StoreCategory']['lft'];
				$conditions['StoreCategory.rght <= '] = $category['StoreCategory']['rght'];
				$conditions["StoreProduct.{$lp}"] = $a['StoreProduct'][$lp] + 1;
				$b = $this->StoreProduct->find('first',array('joins'=>$joins,'conditions'=>$conditions));
			}else{
				$b = null;
			}			
		}
		if(is_array($a) && !empty($a)){
			$a['StoreProduct'][$lp] = (isset($a['StoreProduct'][$lp]) ) ? $a['StoreProduct'][$lp] + 1 : 0;		
			$this->StoreProduct->save($a);
			if(is_array($b) && !empty($b)){
				$b['StoreProduct'][$lp] = (isset($b['StoreProduct'][$lp]) ) ? $b['StoreProduct'][$lp] - 1 : 0;
				$this->StoreProduct->save($b);	
			}			
		}
		$this->redirect($this->referer());
	}	
	
	
}
?>